# -*-coding: Utf-8 -*-
# @File : db_hander .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2023/6/19
from conf import settings
import os
import json


def select(username, roles):
    if roles == 'admin':
        DATA_PATH = os.path.join(settings.DB_PATH, 'Admin_data')
    elif roles == 'user':
        DATA_PATH = os.path.join(settings.DB_PATH, 'User_data')
    elif roles == 'shop':
        DATA_PATH = os.path.join(settings.DB_PATH, 'Goods_data')
    else:
        flow = f'无效身份认证'
        return False, flow
    user_path = os.path.join(DATA_PATH, f'{username}.json')

    # if not os.path.exists(user_path):
    #     flow = f'当前用户 :>>>{username} 不存在,请先注册!!'
    #     return False, flow

    if os.path.exists(user_path):
        with open(user_path, 'r', encoding='utf-8') as f:
            data_dict = json.load(f)
            return data_dict


def save(username, data_dict, roles):
    if roles == 'admin':
        DATA_PATH = os.path.join(settings.DB_PATH, 'Admin_data')
    elif roles == 'user':
        DATA_PATH = os.path.join(settings.DB_PATH, 'User_data')
    elif roles == 'shop':
        DATA_PATH = os.path.join(settings.DB_PATH, 'Goods_data')

    else:
        flow = f'无效身份认证'
        return False, flow

    if not os.path.exists(DATA_PATH):
        os.mkdir(DATA_PATH)

    user_path = os.path.join(DATA_PATH, f'{username}.json')

    with open(user_path, 'w', encoding='utf-8') as fp:
        json.dump(data_dict, fp, ensure_ascii=False)

    flow = f'当前用户:>>>{username} 注册成功!!'
    return True, flow
